import React, { Component } from "react";
import MainLayout from "../../../component/mainLayout/mainLayout";
import { DatePicker, ListView } from "antd-mobile";
import { StickyContainer, Sticky } from "react-sticky";
import dataImg from "@/images/icon/data.png";
import top from "@/images/icon/top_active.png";
import bottom from "@/images/icon/bottom_active.png";
import XHQBConfig from "../../../config/XHQBConfig";
import yhTools from "../../../tools/yh";
import { Toast } from "antd-mobile";
import "./style.scss";
import NoData from "@/component/noData/noData";
const data = [
	{
		img: "https://zos.alipayobjects.com/rmsportal/dKbkpPXKfvZzWCM.png",
		title: "Meet hotel",
		des: "不是所有的兼职汪都需要风吹日晒"
	},
	{
		img: "https://zos.alipayobjects.com/rmsportal/XmwCzSeJiqpkuMB.png",
		title: "McDonald's invites you",
		des: "不是所有的兼职汪都需要风吹日晒"
	},
	{
		img: "https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png",
		title: "Eat the week",
		des: "不是所有的兼职汪都需要风吹日晒"
	}
];
const NUM_SECTIONS = 5;
const NUM_ROWS_PER_SECTION = 5;
let pageIndex = 0;

const dataBlobs = {};
let sectionIDs = [];
let rowIDs = [];
function genData(pIndex = 0) {
	for (let i = 0; i < NUM_SECTIONS; i++) {
		const ii = pIndex * NUM_SECTIONS + i;
		const sectionName = `11111 ${ii}`;
		sectionIDs.push(sectionName);
		dataBlobs[sectionName] = sectionName;
		rowIDs[ii] = [];

		for (let jj = 0; jj < NUM_ROWS_PER_SECTION; jj++) {
			const rowName = `2222${ii}, 3333${jj}`;
			rowIDs[ii].push(rowName);
			dataBlobs[rowName] = rowName;
		}
	}
	sectionIDs = [...sectionIDs];
	rowIDs = [...rowIDs];
}

let nowdate = new Date();
let year = nowdate.getFullYear();
let month = nowdate.getMonth() + 1;
month = month < 10 ? "0" + month : month;
let chooseDate = year + "" + month;

const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
const utcNow = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
let minDate = new Date(nowTimeStamp - 1e7);
const maxDate = new Date(nowTimeStamp + 1e7);
if (minDate.getDate() !== maxDate.getDate()) {
	minDate = new Date(
		maxDate.getFullYear(),
		maxDate.getMonth(),
		maxDate.getDate()
	);
}

const payTools = [
	{
		name: "全部",
		id: "-1"
	},
	{
		name: "小辉付",
		id: "1001"
	},
	{
		name: "快捷支付",
		id: "1003"
	},
	{
		name: "余额支付",
		id: "1004"
	},
	{
		name: "微信支付",
		id: "1005"
	}
];

const tranTypes = [
	{
		name: "全部",
		id: "-1"
	},
	{
		name: "支付",
		id: "0"
	},
	{
		name: "退款",
		id: "1"
	}
];

class WalletBillNew extends React.Component {
	constructor(props) {
		super(props);
		const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
		const getRowData = (dataBlob, sectionID, rowID) => {
			console.log("getRowData", dataBlob);
			dataBlob[rowID];
		};
		console.log("getRowData-->", getRowData);
		console.log("getSectionData-->", getSectionData);
		const dataSource = new ListView.DataSource({
			getRowData,
			getSectionHeaderData: getSectionData,
			rowHasChanged: (row1, row2) => row1 !== row2,
			sectionHeaderHasChanged: (s1, s2) => s1 !== s2
		});
		this.state = {
			page: 0,
			isLoadingMore: false,
			showLoding: true,

			chooseDate: chooseDate,

			date: now,
			time: now,
			utcDate: utcNow,
			dpValue: null,
			customChildValue: null,
			visible: false,

			wayShow: false,
			classifyShow: false,
			itemWayName: "全部",
			itemWayId: "-1",
			itemClassifyName: "全部",
			itemClassifyId: "-1",
			titleData: {},
			data: [],
			dataSource,
			isLoading: true
		};
	}
	componentDidMount() {
		// you can scroll to the specified position
		// setTimeout(() => this.lv.scrollTo(0, 120), 800);

		// simulate initial Ajax
		setTimeout(() => {
			genData();
			this.setState({
				dataSource: this.state.dataSource.cloneWithRowsAndSections(
					dataBlobs,
					sectionIDs,
					rowIDs
				),
				isLoading: false
			});
		}, 600);

		/* document.getElementById("img").parentNode.style.marginLeft = "auto";
        const wrapper = this.refs.wrapper;
        const loadMoreDataFn = this.loadMoreDataFn;
        const that = this; // 为解决不同context的问题
        let timeCount;
        function callback() {
            const top = wrapper.getBoundingClientRect().top;
            const windowHeight = window.screen.height;
            if (top && top < windowHeight) {
                // 当 wrapper 已经被滚动到页面可视范围之内触发
                loadMoreDataFn(that);
            }
        }
        window.addEventListener(
            "scroll",
            function () {
                if (this.state.isLoadingMore) {
                    return;
                }
                if (timeCount) {
                    clearTimeout(timeCount);
                }
                timeCount = setTimeout(callback, 2000);
            }.bind(this),
            false
        );
         */
		this.setState({
			billData: []
		});
		//this.goList();
	}

	loadMoreDataFn(that) {
		console.log(111111);

		let page = that.state.page;
		page++;
		let objs = {
			url: XHQBConfig.moneyBill,
			params: {
				pageIndex: page,
				pageLimit: 10,
				pageSize: 10,
				payTools: [that.state.itemWayId + ""],
				timeString: that.state.chooseDate,
				tranTypes: [that.state.itemClassifyId + ""]
			}
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			console.log("res===", res);
			let listData = [];
			if (res.resCode === 200) {
				if (res.data.billVos && res.data.billVos.length > 0) {
					listData = that.state.data.concat(res.data.billVos);
					that.setState({
						page: page,
						data: listData,
						showLoding: true
					});
				} else {
					that.setState({
						showLoding: false
					});
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
		// that.setState({
		// 	data: that.state.data.concat(["E", "c", "h", "o"])
		// });
	}

	goList() {
		let objs = {
			url: XHQBConfig.moneyBill,
			params: {
				pageIndex: 0,
				pageLimit: 10,
				pageSize: 10,
				payTools: [this.state.itemWayId + ""],
				timeString: this.state.chooseDate,
				tranTypes: [this.state.itemClassifyId + ""]
			}
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			console.log("res===", res);
			let listData = [];
			if (res.resCode === 200) {
				if (res.data.billVos && res.data.billVos.length > 0) {
					this.setState({
						data: res.data.billVos
					});
					// res.data.billVos.forEach(item => {
					// 	listData.push(item);
					// 	this.setState({
					// 		data: listData
					// 	});
					// 	// if (item.isSummary == "1") {
					// 	// 	this.setState({
					// 	// 		titleData: item || {}
					// 	// 	});
					// 	// 	console.log("thus.titleData", this.state.titleData);
					// 	// } else if (item.isSummary == "0") {

					// 	// }
					// 	// console.log("titleData===", this.state.titleData);
					// 	// console.log("data===", this.state.data);
					// });
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	onChange(date) {
		let nowdate = new Date(date);
		let year = nowdate.getFullYear();
		let month = nowdate.getMonth() + 1;
		month = month < 10 ? "0" + month : month;
		let chooseDate = year + "" + month;
		this.setState(
			{
				chooseDate: chooseDate
			},
			() => {
				this.goList();
			}
		);
		console.log("date===", date);
		console.log("chooseDate====", chooseDate);
	}
	// 打开 支付方式
	showPeriods() {
		this.setState({
			wayShow: true,
			classifyShow: false
		});
	}
	showClassify() {
		this.setState({
			classifyShow: true,
			wayShow: false
		});
	}
	onFalse() {
		this.setState({
			classifyShow: false,
			wayShow: false
		});
	}
	itemWay(item) {
		this.setState(
			{
				itemWayName: item.name,
				itemWayId: item.id,
				wayShow: false
			},
			() => {
				this.goList();
			}
		);
		console.log("item", item.name);
	}
	itemClassify(item) {
		this.setState(
			{
				itemClassifyName: item.name,
				itemClassifyId: item.id,
				classifyShow: false
			},
			() => {
				this.goList();
			}
		);
		console.log("item", item);
	}

	onEndReached = event => {
		// load new data
		// hasMore: from backend data, indicates whether it is the last page, here is false
		if (this.state.isLoading && !this.state.hasMore) {
			return;
		}
		console.log("reach end", event);
		this.setState({ isLoading: true });
		setTimeout(() => {
			genData(++pageIndex);
			this.setState({
				dataSource: this.state.dataSource.cloneWithRowsAndSections(
					dataBlobs,
					sectionIDs,
					rowIDs
				),
				isLoading: false
			});
		}, 1000);
	};

	render() {
		let {
			wayShow,
			classifyShow,
			itemWayName,
			itemWayId,
			itemClassifyName,
			itemClassifyId,

			titleData,
			isLoadingMore
		} = this.state;
		let noDataObj = {
			type: "replaceList",
			msg: "暂无数据"
		};

		const headerParams = {
			header: {
				title: "钱包账单",
				headerBackground: "#ffffff",
				titleColor: "#000000",
				backButtColor: "backButtColor",
				newBackButt: true
			},
			history: this.props.history
		};

		const separator = (sectionID, rowID) => (
			<div
				key={`${sectionID}-${rowID}`}
				style={{
					backgroundColor: "#F5F5F9",
					height: 8,
					borderTop: "1px solid #ECECED",
					borderBottom: "1px solid #ECECED"
				}}
			/>
		);
		let index = data.length - 1;
		const row = (rowData, sectionID, rowID) => {
			if (index < 0) {
				index = data.length - 1;
			}
			const obj = data[index--];
			return (
				<div className="listCont" key={rowID}>
					{/* <div style={{ padding: '0 15px' }}>
						<div
							style={{
								lineHeight: '50px',
								color: '#888',
								fontSize: 18,
								borderBottom: '1px solid #F6F6F6',
							}}
						>{obj.title}</div>
						<div style={{ display: '-webkit-box', display: 'flex', padding: '15px 0' }}>
							<img style={{ height: '64px', marginRight: '15px' }} src={obj.img} alt="" />
							<div style={{ lineHeight: 1 }}>
								<div style={{ marginBottom: '8px', fontWeight: 'bold' }}>{obj.des}</div>
								<div><span style={{ fontSize: '30px', color: '#FF6E27' }}>35</span>¥ {rowID}</div>
							</div>
						</div>
					</div> */}
					<div className="list">
						<div className="name">
							<div>{"1111"}</div>
							<div>10000</div>
						</div>
						<div className="time">
							<div>{222222}</div>
							<div>
								<div>支付</div>
							</div>
						</div>
					</div>
				</div>
			);
		};
		return (
			<div className="page-walletBillPage">
				<MainLayout pageParams={headerParams}>
					<div className="walletBillPage">
						<div className="titleCont">
							<div className="left" onClick={this.showPeriods.bind(this)}>
								{wayShow ? (
									<div className="name color">{itemWayName}</div>
								) : (
									<div className="name">{itemWayName}</div>
								)}
								<img src={wayShow ? top : bottom} alt="" />
							</div>
							<div className="right" onClick={this.showClassify.bind(this)}>
								{classifyShow ? (
									<div className="name color">{itemClassifyName}</div>
								) : (
									<div className="name">{itemClassifyName}</div>
								)}
								<img src={classifyShow ? top : bottom} alt="" />
							</div>

							<DatePicker
								mode="month"
								title="选择日期"
								extra="Optional"
								format="yyyy-mm"
								value={this.state.date}
								onChange={this.onChange.bind(this)}
							>
								<img className="img" id="img" src={dataImg} alt="" />
							</DatePicker>
						</div>
						{wayShow ? (
							<div>
								<div className="mask" onClick={this.onFalse.bind(this)}></div>
								<div className="itemCont">
									{payTools.map((item, index) => {
										return (
											<div
												key={index}
												className={
													this.state.itemWayId === item.id ? "active" : "item"
												}
												onClick={this.itemWay.bind(this, item)}
											>
												{item.name}
											</div>
										);
									})}
								</div>
							</div>
						) : null}
						{classifyShow ? (
							<div>
								<div className="mask" onClick={this.onFalse.bind(this)}></div>
								<div className="itemCont">
									{tranTypes.map((item, index) => {
										return (
											<div
												key={index}
												className={
													this.state.itemClassifyId === item.id
														? "active"
														: "item"
												}
												onClick={this.itemClassify.bind(this, item)}
											>
												{item.name}
											</div>
										);
									})}
								</div>
							</div>
						) : null}
						<div className="line"></div>
						<ListView
							dataSource={this.state.dataSource}
							className="am-list sticky-list"
							useBodyScroll
							renderSectionWrapper={sectionID => (
								<StickyContainer
									key={`s_${sectionID}_c`}
									className="sticky-container"
									style={{ zIndex: 4 }}
								/>
							)}
							renderSectionHeader={sectionData => (
								<Sticky>
									{({ style }) => (
										<div>
											{/* <div
												className="sticky"
												style={{
													...style,
													zIndex: 3,
													backgroundColor: parseInt(sectionData.replace('Section ', ''), 10) % 2 ?
														'#5890ff' : '#F8591A',
													color: 'white',
													top: '2.28rem'
												}}
											>{`Task ${sectionData.split(' ')[1]}`}</div> */}
											<div className="listCont">
												<div
													className="sticky"
													style={{
														...style,
														zIndex: 3,
														backgroundColor:
															parseInt(
																sectionData.replace("Section ", ""),
																10
															) % 2
																? "#5890ff"
																: "#F8591A",
														color: "white",
														top: "2.28rem"
													}}
												>
													<div className="dataTitle">{`Task ${
														sectionData.split(" ")[1]
													}`}</div>
												</div>
											</div>
										</div>
									)}
								</Sticky>
							)}
							renderFooter={() => (
								<div style={{ padding: 30, textAlign: "center" }}>
									{this.state.isLoading ? "Loading..." : "Loaded"}
								</div>
							)}
							renderRow={row}
							renderSeparator={separator}
							pageSize={4}
							onScroll={() => {
								console.log("scroll");
							}}
							scrollEventThrottle={200}
							onEndReached={this.onEndReached}
							onEndReachedThreshold={10}
						/>
						<div className="listCont">
							{/* {data && data.length > 0 && data.map((item, index) => {
								return (
									<div key={index}>
										{item.isSummary == "1" ? (
											<div className="sticky">
												<div className="dataTitle">{item.payDesc}</div>
											</div>
										) : null}

										{item.isSummary == "0" ? (
											<div className="list">
												<div className="name">
													<div>{item.payToolName}</div>
													<div>
														{`${item.tranType == "0" ? "-" : "+"}${item.tranAmount
															? parseFloat(item.tranAmount / 100).toFixed(2)
															: "0.00"
															}`}
													</div>
												</div>
												<div className="time">
													<div>{item.tranTime}</div>
													<div>
														{item.tranType === "0" ? (
															<div>支付</div>
														) : (
															<div>退款</div>
														)}
													</div>
												</div>
											</div>
										) : null}
									</div>
								);
							})} */}
						</div>
						{/* {isLoadingMore == true ? (
							<div
								className="loadMore"
								ref="wrapper"
								onClick={this.loadMoreDataFn.bind(this, this)}
							>
								正在加载···
							</div>
						) : null} */}
						{this.state.data.length == 0 && <NoData params={noDataObj} />}
					</div>
				</MainLayout>
			</div>
		);
	}
}
export default WalletBillNew;
